/**业务管理流程平台版本1.0,生成时间:2017-04-13 13:16:48**/
package com.xbdun.service.bmp.service.system.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xbdun.common.api.Client;
import com.xbdun.common.enums.PkGenerateEnum;
import com.xbdun.common.enums.UserRolesEnums;
import com.xbdun.common.enums.YesOrNoEnum;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.page.Pager;
import com.xbdun.common.util.CommonUtil;
import com.xbdun.common.util.DateUtil;
import com.xbdun.common.util.PkGenerator;
import com.xbdun.dao.bmp.entity.XbdunSysOrgDo;
import com.xbdun.dao.bmp.entity.XbdunSysUserDo;
import com.xbdun.facade.bmp.constant.SysOrgConst;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgAuditingStatusEnum;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgEnableEnum;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgVailEmailEnum;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.request.system.SysOrgAuditingRequest;
import com.xbdun.facade.bmp.request.system.SysOrgModifyRequest;
import com.xbdun.facade.bmp.request.system.SysOrgPagerRequest;
import com.xbdun.facade.bmp.request.system.SysOrgRequest;
import com.xbdun.facade.bmp.response.system.SysOrgResponse;
import com.xbdun.service.bmp.biz.SysOrgBiz;
import com.xbdun.service.bmp.biz.SysUserBiz;
import com.xbdun.service.bmp.service.cache.OrgInfoCacheService;
import com.xbdun.service.bmp.service.system.SysOrgService;

import lombok.extern.slf4j.Slf4j;

/**
 * 企业信息
 * 
 * @ClassName XbdunSysOrgServiceImpl
 * @author 张国涛 @2017-04-13 13:16:48
 */
@Service
@Transactional
@Slf4j
public class SysOrgServiceImpl implements SysOrgService {
	@Autowired
	private SysOrgBiz sysOrgBiz;
	@Autowired
	private SysUserBiz sysUserBiz;
	@Autowired
	OrgInfoCacheService orgInfoCacheService;
	/**
	* @Title: getSysOrgByOrgCode
	* @Description: 根据orgCode查询机构信息
	* @param orgCode
	* @return SysOrgResponse    返回类型
	* @throws
	 */
	public SysOrgResponse getSysOrgByOrgCode(long orgCode)throws Exception{
		if (orgCode <= 0 ) throw BizException.PARAM_CHKE_FAIL.newInstance("机构orgCode不能小于等于零");
		XbdunSysOrgDo xbdunSysOrgByOrgCode = sysOrgBiz.getSysOrgByOrgCode(orgCode);
		if ( null == xbdunSysOrgByOrgCode ) {
			throw BizException.DB_SELECTONE_IS_NULL;
		}
		// 资源Copy
		SysOrgResponse response = new SysOrgResponse();
		BeanUtils.copyProperties(response, xbdunSysOrgByOrgCode);
		return response;
	}
	
	/**
	 * 新增企业信息
	 * @param request
	 */
	public Long addSysOrg(SysOrgRequest request) throws Exception {

		XbdunSysOrgDo xbdunSysOrgDo = new XbdunSysOrgDo();
		BeanUtils.copyProperties(xbdunSysOrgDo, request);
		
		if (sysOrgBiz.existSysOrg(xbdunSysOrgDo) > 0) {
			throw BmpBizException.DEF_ERROR.newInstance("企业名称/企业邮箱/备案号其中一个已经存在了");
		}
		long userCode = PkGenerator.generateLongPk(PkGenerateEnum.SYSFRAME);
		
		xbdunSysOrgDo.setUserCode(userCode);
		xbdunSysOrgDo.setOrgCode(SysOrgConst.INIT_ORG_CODE);
		xbdunSysOrgDo.setLimitPers(SysOrgConst.ORG_PERSON_LIMIT);
		xbdunSysOrgDo.setValiEmail(SysOrgVailEmailEnum.NO_VERIFY.getKey());
		xbdunSysOrgDo.setAuditingStatus(SysOrgAuditingStatusEnum.DEFAULT.getKey());
		xbdunSysOrgDo.setEnable(SysOrgEnableEnum.OFF.getKey());
		xbdunSysOrgDo.setUnionid(request.getUnionid());// 设置微信id
		xbdunSysOrgDo.setCreateTime(new Date());
		log.info("新增企业基本信息 {}", JSON.toJSONString(xbdunSysOrgDo));
		Long addXbdunSysOrgInfo = sysOrgBiz.addXbdunSysOrg(xbdunSysOrgDo);
		if (null == addXbdunSysOrgInfo || addXbdunSysOrgInfo.longValue() <= 0) {
			throw BmpBizException.DB_INSERT_RESULT_0;
		}
		
		//验证通过后, 添加企业信息的同时创建并添加企业法人到平台用户中
		XbdunSysUserDo xbdunSysUserDo = new XbdunSysUserDo();
		
		xbdunSysUserDo.setUserCode(userCode);//用户编号
		xbdunSysUserDo.setUserName("xbduncom");
		xbdunSysUserDo.setRealName(request.getBusiPerson());//设置真实姓名
		xbdunSysUserDo.setEmail(request.getOrgEmail());//设置邮箱
		xbdunSysUserDo.setPwd(request.getPwd());//设置密码
		xbdunSysUserDo.setUnionid(request.getUnionid());// 设置微信id
		xbdunSysUserDo.setXcxOpenId(request.getXcxOpenId());//微信用户ID
		xbdunSysUserDo.setIdCard(request.getIdCard());//设置IDCard
		xbdunSysUserDo.setType(UserRolesEnums.SUPPERADMIN.getKey());//默认第一次用户的注册肯定是超级管理员
		xbdunSysUserDo.setCreateTime(new Date());
		if(NumberUtils.isDigits(request.getLatitude())){
			xbdunSysUserDo.setLatitude(NumberUtils.createBigDecimal(request.getLatitude()));
		}
		if(NumberUtils.isDigits(request.getLongitude())){
			xbdunSysUserDo.setLongitude(NumberUtils.createBigDecimal(request.getLongitude()));
		}
		//设置密码
		xbdunSysUserDo.setPwd(CommonUtil.settingPwd(request.getPwd(),DateUtil.formatDate(xbdunSysUserDo.getCreateTime())));
		log.info("新增企业用户信息{}",JSON.toJSONString(xbdunSysUserDo));
		sysUserBiz.getSysUserOrCreate(xbdunSysUserDo,request.getOrgMobile());
		return addXbdunSysOrgInfo;
	}

	/**
	* @Title: queryPager
	* @Description: 分页查询
	* @param requestPager	请求参数
	* @return Pager<SysOrgResponse>    返回类型
	 */
	public Pager<SysOrgResponse> queryPager(SysOrgPagerRequest requestPager,Client client) throws Exception{
		Map<String,Object> where  = new HashMap<String,Object>();
		
		if (requestPager.getAuditingStatus() > 0) {
			where.put("auditingStatus", requestPager.getAuditingStatus());// 审核状态
		}
		if (requestPager.getEnable() != 0) {
			where.put("enable", requestPager.getEnable());// 停用/启用
		}
		if (requestPager.getSelectKey()>=0&&StringUtils.isNotBlank(requestPager.getSelectValue())) {
			where.put("selectKey", requestPager.getSelectKey());
			where.put("selectValue", requestPager.getSelectValue());
		}
		//开始时间
		if(null!=requestPager.getStartDate()){
			where.put("startDate",requestPager.getStartDate());
		}
		//结束时间
		if(null!=requestPager.getEndDate()){
			where.put("endDate",requestPager.getEndDate());
		}
		//是否代理机构
		if(requestPager.getBlAgentOrg()>0){
			where.put("blAgentOrg", requestPager.getBlAgentOrg());
		}
		//排序
		if(StringUtils.isBlank(requestPager.getOrderBy())){
			requestPager.setOrderBy(" blAgentOrg ASC , createTime DESC");
		}
		if(StringUtils.isNotBlank(requestPager.getOrderBy())){
			requestPager.setOrderBy(" blAgentOrg ASC ," + requestPager.getOrderBy());
		}
		Pager<SysOrgResponse> queryPager = sysOrgBiz.queryPager(where, requestPager.getOrderBy(), requestPager.getPageIndex(), requestPager.getPageSize());
		where.clear();
		where = null;
		return queryPager;
	}

	/**
	* @Title: modifySysOrg
	* @Description: 修改机构信息
	* @param sysOrgModifyRequest	机构信息
	* @throws Exception
	 */
	@Transactional
	public void modifySysOrg(SysOrgModifyRequest sysOrgModifyRequest,Client client)throws Exception{
		XbdunSysOrgDo xbdunSysOrgDo = new XbdunSysOrgDo();
		if (sysOrgModifyRequest.getAuditingStatus() == null) {
			sysOrgModifyRequest.setAuditingStatus(0);
		}
		
		if (sysOrgModifyRequest.getEnable() == null) {
			sysOrgModifyRequest.setEnable(0);
		}
		BeanUtils.copyProperties(xbdunSysOrgDo, sysOrgModifyRequest);
		
		sysOrgBiz.updateOrgInfo(xbdunSysOrgDo,client);
		orgInfoCacheService.removeSingleOrgInfo(client.getOrgCode());
	}
	/**
	* @Title: modifyAgentOrg
	* @Description: 设置代理机构
	* @param orgCode		机构编编号
	* @param yesOrNoEnum	是否为代理机构
	* @return void    返回类型
	 */
	@Transactional
	public void modifyAgentOrg(long orgCode,YesOrNoEnum yesOrNoEnum)throws Exception{
		
		sysOrgBiz.modifyAgentOrg(orgCode, yesOrNoEnum.getKey());
	}
	//================================================
	
	/**
	* 机构审核
	* @Title: auditingSysOrg
	* @Description: 机构审核
	* @param request	请求对象
	* @param client		客户端
	* @return XbdUnStringResult    返回类型
	 */	
	public void auditingSysOrg(SysOrgAuditingRequest request,Client client)throws Exception{
		//判断是否存在该企业
		XbdunSysOrgDo sysOrgDo = sysOrgBiz.getOrgById(request.getId());
		if (sysOrgDo==null) {
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("未查询到指定机构");
		}
		if (client.getRoleId()!=5) {
			throw BizException.POWER_FAIL.newInstance("对不起,您当前无权限修改");
		}
		
		sysOrgDo.setAuditingStatus(request.getAuditingStatus());
		sysOrgDo.setRemarks(request.getRemarks());
		sysOrgBiz.auditingSysOrg(sysOrgDo,client);
	}
}